//
//  UpdateUserNameViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/15.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "UpdateUserNameViewController.h"
#import "BLHeader.h"
#import <Masonry.h>
#import "UpdateNet.h"
#import <MBProgressHUD.h>

@interface UpdateUserNameViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
@property (nonatomic, strong) NSString *userName;

@end

@implementation UpdateUserNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.title = @"修改用户名";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(commitUpdate)];
    [right setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:kAppThemeColor ,NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    self.userName = [[NSUserDefaults standardUserDefaults] objectForKey:USERNAME];
    self.userNameField.text = self.userName;
}



- (void)commitUpdate {
    NSString *newName = self.userNameField.text;
    if(!newName || newName.length == 0) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"用户名不能为空或超过16个字";
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    NSString *tel = [[NSUserDefaults standardUserDefaults] objectForKey:USERTEL];
    NSDictionary *param = @{@"userName":newName, @"userTel": tel};
    
    __weak typeof (self) weakSelf = self;
    [UpdateNet updateUserInfo:param completer:^(id resultObject, NSError *error) {
        if(resultObject) {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"修改成功";
             [[NSNotificationCenter defaultCenter] postNotificationName:@"updateHeadView" object:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            return ;
        }
        [hud hideAnimated:YES];
    }];

}
@end
